import React, { useReducer, useState, useEffect, Fragment } from 'react';
import { Card, Icon, Modal, notification, Button } from 'antd';
import Link from 'umi/link';
import Zmage from 'react-zmage';
import { SIZE, PAGE, ALL, IconUrl } from '@/utils/constant';
import { classList, gradesList, delClases } from '@/services/api';
import MyForm from './components/MyForm';
import TableList from './components/TableList';

interface initial {
  loading: boolean;
  data: [];
  pagination: object;
  searchValue: object;
}

const initialState: initial = {
  loading: false,
  data: [],
  pagination: {
    showSizeChanger: true,
  },
  searchValue: {},
};

const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: IconUrl, // 在 iconfont.cn 上生成
});

const reducer = (state: any, { type, payload }: any) => {
  switch (type) {
    case 'OPEN_LOADING':
      return {
        ...state,
        loading: true,
      };
    case 'CLOSED_LOADING':
      return {
        ...state,
        loading: false,
      };
    case 'GET_DATA':
      return {
        ...state,
        data: payload,
      };
    case 'CHANGE_PAGINATION':
      return {
        ...state,
        pagination: payload,
      };
    case 'SEARCH_VALUE':
      return {
        ...state,
        searchValue: payload,
      };
    default:
      return state;
  }
};

const List = (props: any) => {
  const [gradesData, setGradesData] = useState([]);
  const [{ loading, data, pagination, searchValue }, dispatch]: any = useReducer(
    reducer,
    initialState,
  );
  const pager = JSON.parse(JSON.stringify(pagination));
  useEffect(() => {
    gradesList({ page: PAGE, size: ALL }).then((res: any) => {
      if (res.status === 'success') {
        setGradesData(res.data.data);
      }
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    classList({ page: PAGE, size: SIZE })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  }, []);

  const onChange = (changePagination: any) => {
    pager.current = changePagination.current;
    pager.pageSize = changePagination.pageSize;
    dispatch({
      type: 'CHANGE_PAGINATION',
      payload: pager,
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    classList({ ...searchValue, page: changePagination.current, size: changePagination.pageSize })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  };

  const columns = [
    {
      title: '年级',
      key: 'grade',
      dataIndex: 'grade',
      render: (text: any) => <span>{text.name || ''}</span>,
    },
    {
      title: '班级名称',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '班主任',
      key: 'teacher',
      dataIndex: 'teacher',
      render: (text: any) => text && <span>{text.name || ''}</span>,
    },
    {
      title: '二维码',
      key: 'image',
      width: 300,
      dataIndex: 'image',
      render: (text: any) => {
        if (text) {
          return text && <Zmage style={{ width: '200px', height: '200px' }} src={text.url} />;
        }
        return null;
      },
    },
    {
      title: '创建时间',
      key: 'created_at',
      dataIndex: 'created_at',
    },
    {
      title: '修改时间',
      key: 'updated_at',
      dataIndex: 'updated_at',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: (text: boolean) =>
        text ? (
          <span>
            <MyIcon type="icon-tubiaozhizuo--open" />
            开启
          </span>
        ) : (
          <span>
            <MyIcon type="icon-tubiaozhizuo--closed" />
            关闭
          </span>
        ),
    },
    {
      title: '操作',
      width: 200,
      key: 'option',
      valueType: 'option',
      dataIndex: 'id',
      render: (text: any, object: any) => (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Link
            to={`/teachingSystem/detail/${text}`}
            onClick={() => {
              sessionStorage.setItem('clasesData', JSON.stringify(object));
            }}
          >
            详情
          </Link>
          <Link
            to="/teachingSystem/editClass"
            onClick={() => {
              sessionStorage.setItem('clasesData', JSON.stringify(object));
            }}
          >
            编辑
          </Link>
          <a
            onClick={e => {
              e.preventDefault();
              Modal.confirm({
                content: '确认删除？',
                onOk: () => {
                  delClases(text).then((resp: any) => {
                    if (resp.data) {
                      notification.success({
                        message: '删除成功',
                      });
                      dispatch({
                        type: 'OPEN_LOADING',
                      });
                      classList({ ...searchValue, page: pager.current, size: pager.pageSize })
                        .then((res: any) => {
                          if (res.status === 'success') {
                            dispatch({
                              type: 'GET_DATA',
                              payload: res.data.data,
                            });
                            dispatch({
                              type: 'CHANGE_PAGINATION',
                              payload: {
                                ...pager,
                                total: res.data.meta.total,
                              },
                            });
                          }
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        })
                        .catch(() => {
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        });
                    }
                  });
                },
              });
            }}
          >
            删除
          </a>
        </div>
      ),
    },
  ];

  return (
    <Fragment>
      <Card
        title="班级列表"
        extra={
          <Button
            type="primary"
            icon="plus"
            onClick={() => {
              props.history.push('/teachingSystem/addClass');
            }}
          >
            新增班级
          </Button>
        }
      >
        <MyForm dispatch={dispatch} classList={classList} gradesData={gradesData} />
      </Card>
      <Card className="pageCard">
        <TableList
          rowKey="id"
          dataSource={data}
          columns={columns}
          loading={loading}
          pagination={pagination}
          onChange={onChange}
        />
      </Card>
    </Fragment>
  );
};

export default List;
